package com.bw.dao;

import com.bw.pojo.Car;
import com.bw.util.JDBC;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/***************************
 FileAction:

 CreateTime:2022-04-11 8:30
 Author:Aaking-aline
 ****************************/
public class CarDao {

    public void insertCar(Car car) throws SQLException {
        String sql = "insert into car values(null,?,?,?,?,?,?,?)";
        Connection connection = JDBC.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);

        ps.setObject(1,car.getCar_name());
        ps.setObject(2,car.getCar_kind());
        ps.setObject(3,car.getCar_price());
        ps.setObject(4,car.getCar_store());
        ps.setObject(5,car.getCar_make_date());
        ps.setObject(6,car.getCar_make_addr());
        ps.setObject(7,car.getCar_number());

        ps.executeUpdate();
    }

    public List<Car> selectCarByLimit(String page) throws SQLException {
        int index = (Integer.parseInt(page) - 1) * 5;
        String sql = "select * from car limit " + index + ",5";

        Connection connection = JDBC.getConnection();

        PreparedStatement ps = connection.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        List<Car> list = new ArrayList<>();

        while(rs.next()){
            Car car = new Car(rs.getInt(1),
                    rs.getString(2),
                    rs.getString(3),
                    rs.getDouble(4),
                    rs.getInt(5),
                    rs.getString(6),
                    rs.getString(7),
                    rs.getString(8));
            list.add(car);
        }

        return list;
    }

    public int selectNum() throws SQLException {
        String sql = "select count(*) from car";

        Connection connection = JDBC.getConnection();

        PreparedStatement ps = connection.prepareStatement(sql);

        ResultSet rs = ps.executeQuery();

        if(rs.next()){
            return rs.getInt(1);
        }

        return 0;
    }

    public void deleteCar(String id) throws SQLException {
        String sql = "delete from car where id in(" + id + ")";
        Connection connection = JDBC.getConnection();
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.executeUpdate();
    }
}
